﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows.Input;
using churchtool.ViewModel;
using Microsoft.Win32;
using System.IO;

namespace churchtool.Operations.Commands
{
    class LoadPluginCommand : ICommand
    {
        #region Fields

        public static string PLUGIN_PATH_CONSTANT = "PlugIns";

        // Member variables
        private SettingsWindowViewModel m_ViewModel;
        private string assemblyPath;

        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor.
        /// </summary>
        public LoadPluginCommand(SettingsWindowViewModel viewModel)
        {
            m_ViewModel = viewModel;
        }

        #endregion

        #region ICommand Members

        /// <summary>
        /// Whether the DoBrowseFilesCommand is enabled.
        /// </summary>
        public bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// Actions to take when CanExecute() changes.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Executes the DoBrowseFilesCommand
        /// </summary>
        public void Execute(object parameter)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog { Multiselect = false };
            if (openFileDialog.ShowDialog() ?? false)
            {
                FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                if (fileInfo.Exists)
                {
                    // Create plugins path
                    var plugInsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), PLUGIN_PATH_CONSTANT);
                    fileInfo.CopyTo(string.Format("{0}{1}{2}", plugInsPath, fileInfo.Name, fileInfo.Extension));
                }
            }
        }

        #endregion
    }
}
